package com.dongliushui.util;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

/**
 * @ClassName: VelocityHelper
 * @Description: velocity帮助类
 * @author zhutulang
 * @date 2016年2月3日
 * @version V1.0
 */
public class VelocityHelper {

	private static final Logger log = Logger.getLogger(VelocityHelper.class);
	/**
	 * velocity引擎
	 */
	private static VelocityEngine ve = null;
	
	/**
	 * <p>Title: init<／p>
	 * <p>Description:velocity引擎初始化  <／p>
	 * @author zhutulang
	 * @version 1.0
	 * @param string 
	 */
	public static synchronized void init(String path) {
	    if (null == ve){
		    try{
		        ve = new VelocityEngine();
		        Properties localProperties = new Properties();
		        localProperties.load(VelocityEngine.class.getClassLoader().getResourceAsStream("velocity.properties"));
		        localProperties.setProperty("file.resource.loader.path", path + localProperties.getProperty("file.resource.loader.path"));
		        ve.init(localProperties);
		        log.info("file.resource.loader.path="+localProperties.get("file.resource.loader.path"));
		        log.info("velocity引擎初始化成功。");
		      } catch (Exception localException){
		        log.fatal("velocity引擎初始化错误。", localException);
		        throw new RuntimeException("velocity引擎初始化错误。", localException);
		      }
	    }
	 }
	
	/** 
	 * <p>Title: getXmlFromResponseMsg<／p>
	 * <p>Description:根据velocity模板生成xml <／p>
	 * @param vmName 模板名称
	 * @param responseMsg 响应消息对象
	 * @return
	 * @author zhutulang
	 * @version 1.0
	 */
	public static String getXmlFromResponseMsg(String vmName, Object responseMsg) {
	    StringWriter stringWriter = null;
		try {
		  stringWriter = new StringWriter();
	      Template localTemplate = ve.getTemplate(vmName, "UTF-8");
	      HashMap<String,Object> localHashMap = new HashMap<String, Object>();
	      localHashMap.put("RespMsg", responseMsg);
	      localTemplate.merge(new VelocityContext(localHashMap), stringWriter);
	      stringWriter.flush();
	    }catch (Exception localException){
	      log.error("从Velocity模板生成相应XML时发生错误。", localException);   
	    }
	    return stringWriter.toString();
	}
}
